<?php

namespace app\common\model\goods;

use think\Db;
use think\Exception;
use think\Model;
use think\Request;


class Goods extends Model
{
    const STATUS_HIDDEN = 0;
    const STATUS_NORMAL = 1;

    // 表名
    protected $name = 'goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    /**
     * 计算显示销量 (初始销量 + 实际销量)
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getGoodsSalesAttr($value, $data)
    {
        return $data['sales_initial'] + $data['sales_actual'];
    }

    /**
     * 筛选
     * @return Goods
     */
    public function validWhere()
    {
        return $this->where('`status`=:status and is_del=:is_del and merchant_id=:merchant_id')->bind(['status' => self::STATUS_NORMAL, 'is_del' => 0, 'merchant_id' => 0]);
    }

    /**
     * 商品详情
     * @param $goods_id
     * @return Goods|null
     * @throws \think\exception\DbException
     */
    public static function getGoodsDetail($goods_id)
    {
        return self::get($goods_id, ['goodscategory', 'spec', 'spec_rel.spec', 'goodsdelivery.rule']);
    }

    public function goodscategory()
    {
        return $this->belongsTo('app\common\model\goods\Category', 'goods_category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function goodsdelivery()
    {
        return $this->belongsTo('app\admin\model\goods\Delivery', 'delivery_id', 'delivery_id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 关联商品规格关系表
     * @return \think\model\relation\BelongsToMany
     */
    public function specRel()
    {
        return $this->belongsToMany('app\common\model\goods\SpecValue', 'GoodsSpecRel');
    }

    /**
     * 关联商品规格表
     * @return \think\model\relation\HasMany
     */
    public function spec()
    {
        return $this->hasMany('app\common\model\goods\GoodsSpec');
    }

    /**
     * 获取规格信息
     * @param \think\Collection $spec_rel
     * @param \think\Collection $skuData
     * @return array
     */
    public function getManySpecData($spec_rel, $skuData)
    {
        // spec_attr
        $specAttrData = [];
//        foreach ($spec_rel->toArray() as $item) {
        foreach ($spec_rel as $item) {

            if (!isset($specAttrData[$item['spec_id']])) {
                $specAttrData[$item['spec_id']] = [
                    'group_id' => $item['spec']['spec_id'],
                    'group_name' => $item['spec']['spec_name'],
                    'spec_items' => [],
                ];
            }
            $specAttrData[$item['spec_id']]['spec_items'][] = [
                'item_id' => $item['spec_value_id'],
                'spec_value' => $item['spec_value'],
            ];
        }
        // spec_list
        $specListData = [];
//        foreach ($skuData->toArray() as $item) {
        foreach ($skuData as $item) {
            $specListData[] = [
                'goods_spec_id' => $item['goods_spec_id'],
                'spec_sku_id' => $item['spec_sku_id'],
                'rows' => [],
                'form' => [
                    'goods_no' => $item['goods_no'],
                    'goods_price' => $item['goods_price'],
                    'goods_weight' => $item['goods_weight'],
                    'line_price' => $item['line_price'],
                    'stock_num' => $item['stock_num'],
                ],
            ];
        }
        return ['spec_attr' => array_values($specAttrData), 'spec_list' => $specListData];
    }

    /**
     * 获取商品列表
     * @param $data
     * @return array|\think\Paginator
     * @throws \think\exception\DbException
     */
    public function getGoodsList($data)
    {
        list($cateId, $goodsName, $priceOrder, $salesOrder, $new, $page, $limit) = [
            $data['cid'], $data['keyword'], $data['priceOrder'], $data['salesOrder'], $data['new'], $data['page'], $data['limit'] = 12
        ];

        $baseOrder = '';
        $model = $this->validWhere();

        if ($cateId) $model->where('goods_category_id', $cateId);

        if (!empty($goodsName)) $model->where('goods_name', 'LIKE', htmlspecialchars("%$goodsName%"));

        if ($new != 0) $model->where('is_new', 1);

        if ($priceOrder) $baseOrder = $priceOrder == 'desc' ? 'goods_price DESC' : 'goods_price ASC';

        if ($salesOrder) $baseOrder = $salesOrder == 'desc' ? 'sales_actual DESC' : 'sales_actual ASC';

        if ($baseOrder) $baseOrder .= ', ';
        $model->order($baseOrder . 'weigh DESC, createtime DESC');

        $list = $model->field(['id,goods_name,goods_category_id,image,sales_initial,sales_actual','(sales_initial + sales_actual) as goods_sales'])
            ->with(['spec' => function ($query) {
                $query->field('goods_id,goods_price,line_price');
            }])->paginate((int)$limit, false, [
                'query' => Request::instance()->request()
            ]);
        return count($list) ? $list : [];
    }
}
